<script lang="ts" setup>
import { onMounted, ref } from 'vue';

import { useVbenModal } from '@vben/common-ui';
import { useUserStore } from '@vben/stores';

import { useFsAsync, useFsRef } from '@fast-crud/fast-crud';
import { Button, Input, InputGroup } from 'ant-design-vue';

import { UserConfig } from '#/api';
import { getValidateRulesByFs } from '#/api/common/validateByFs';
import { ActionEnum, MsgTemplateCodeEnum } from '#/enums/commonEnum';
import { useMessage } from '#/hooks/web/useMessage';
import { $t } from '#/locales';

import { createCrudOptions, frontRules, useCaptcha } from '../data/email';

defineOptions({
  name: 'SafetyPasswordModal',
  inheritAttrs: false,
});

const { createMessage } = useMessage();
const formRef = ref();
const userStore = useUserStore();

const { crudRef, crudBinding, crudExpose, context } = useFsRef();

onMounted(async () => {
  const { appendCrudOptions } = await useFsAsync({
    crudBinding,
    crudRef,
    crudExpose,
    context,
    createCrudOptions,
  });

  const addFormOptions = await getValidateRulesByFs({
    Api: UserConfig.UpdateEmail,
    mode: ActionEnum.ADD,
    customRules: frontRules(formRef),
  });
  appendCrudOptions({ ...addFormOptions });
});

const { label, isStart, loading, getCaptcha } = useCaptcha(formRef);

const [Modal, modalApi] = useVbenModal({
  async onOpened() {
    const data = userStore.userInfo;

    formRef.value.setFormData(
      { id: data?.id, templateCode: MsgTemplateCodeEnum.EMAIL_EDIT },
      { mergeForm: false },
    );
  },
  onConfirm: handleSubmit,
});

async function handleSubmit() {
  await formRef.value.submit();

  createMessage.success($t(`common.tips.editSuccess`));
  modalApi.close();
}

defineExpose(modalApi);
</script>

<template>
  <Modal title="修改邮箱">
    <div class="p-4">
      <FsForm ref="formRef" v-bind="crudBinding.addForm">
        <template #form_code="scope">
          <InputGroup compact>
            <Input v-model:value="scope.form.code" style="width: 60%" />
            <Button
              style="width: 40%"
              :disabled="isStart"
              :loading="loading"
              @click="getCaptcha(scope.form.email)"
            >
              {{ label }}
            </Button>
          </InputGroup>
        </template>
      </FsForm>
    </div>
  </Modal>
</template>
